<template>
  <div class="api-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>API接口管理</span>
          <el-button type="primary" @click="handleAdd">
            新增API
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <mobile-search 
        :search-form="searchForm" 
        @search="handleSearch" 
        @reset="handleReset"
      >
        <template #default="{ searchForm }">
          <el-form-item label="接口名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入接口名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="请求方法">
            <el-select
              v-model="searchForm.method"
              placeholder="请选择请求方法"
              clearable
            >
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
        </template>
      </mobile-search>

      <!-- 表格区域 -->
      <mobile-table
        :data="tableData"
        :current-page="pagination.page"
        :page-size="pagination.size"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
        <!-- 桌面端表格 -->
        <template #desktop-table>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="接口名称" />
            <el-table-column prop="path" label="接口路径" />
            <el-table-column prop="method" label="请求方法" width="100">
              <template #default="{ row }">
                <el-tag :type="getMethodColor(row.method)">
                  {{ row.method }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="info" size="small" @click="handleTest(row)">
                  测试
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 移动端卡片 -->
        <template #mobile-card="{ row }">
          <div class="api-card">
            <div class="api-header">
              <div class="api-info">
                <h3>{{ row.name }}</h3>
                <p class="api-path">{{ row.method }} {{ row.path }}</p>
              </div>
              <div class="api-status">
                <el-tag :type="getMethodColor(row.method)" size="small">
                  {{ row.method }}
                </el-tag>
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                  size="small"
                />
              </div>
            </div>
            
            <div class="api-details">
              <div class="detail-item" v-if="row.description">
                <span class="label">描述：</span>
                <span class="value">{{ row.description }}</span>
              </div>
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ row.createTime }}</span>
              </div>
            </div>
            
            <div class="api-actions">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="info" size="small" @click="handleTest(row)">
                测试
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </div>
        </template>
      </mobile-table>
    </el-card>

    <!-- API表单对话框 -->
    <mobile-form
      v-model="dialogVisible"
      :title="dialogTitle"
      :loading="submitLoading"
      @confirm="handleSubmit"
      @close="handleDialogClose"
    >
      <el-form
        ref="apiFormRef"
        :model="apiForm"
        :rules="apiRules"
        label-width="100px"
      >
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="apiForm.name" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="接口路径" prop="path">
          <el-input v-model="apiForm.path" placeholder="请输入接口路径，如：/api/users" />
        </el-form-item>
        <el-form-item label="请求方法" prop="method">
          <el-select v-model="apiForm.method" placeholder="请选择请求方法">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="PATCH" value="PATCH" />
          </el-select>
        </el-form-item>
        <el-form-item label="接口描述" prop="description">
          <el-input
            v-model="apiForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入接口描述"
          />
        </el-form-item>
        <el-form-item label="请求参数" prop="requestParams">
          <el-input
            v-model="apiForm.requestParams"
            type="textarea"
            :rows="4"
            placeholder="请输入请求参数（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="响应示例" prop="responseExample">
          <el-input
            v-model="apiForm.responseExample"
            type="textarea"
            :rows="4"
            placeholder="请输入响应示例（JSON格式）"
          />
        </el-form-item>
      </el-form>
    </mobile-form>

    <!-- API测试对话框 -->
    <mobile-form
      v-model="testDialogVisible"
      title="API测试"
      :loading="testLoading"
      @confirm="handleApiTest"
    >
      <div class="api-test-container">
        <div class="test-info">
          <p><strong>接口：</strong>{{ currentApi.method }} {{ currentApi.path }}</p>
          <p><strong>描述：</strong>{{ currentApi.description }}</p>
        </div>
        
        <el-form label-width="100px">
          <el-form-item label="请求参数">
            <el-input
              v-model="testParams"
              type="textarea"
              :rows="6"
              placeholder="请输入测试参数（JSON格式）"
            />
          </el-form-item>
        </el-form>
        
        <div v-if="testResult" class="test-result">
          <h4>测试结果：</h4>
          <pre>{{ testResult }}</pre>
        </div>
      </div>
    </mobile-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MobileTable from '@/components/MobileTable/index.vue'
import MobileForm from '@/components/MobileForm/index.vue'
import MobileSearch from '@/components/MobileSearch/index.vue'

const loading = ref(false)
const dialogVisible = ref(false)
const testDialogVisible = ref(false)
const submitLoading = ref(false)
const testLoading = ref(false)
const apiFormRef = ref()

const searchForm = reactive({
  name: '',
  method: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const apiForm = reactive({
  id: null,
  name: '',
  path: '',
  method: '',
  description: '',
  requestParams: '',
  responseExample: ''
})

const currentApi = ref({})
const testParams = ref('')
const testResult = ref('')

const dialogTitle = computed(() => {
  return apiForm.id ? '编辑API' : '新增API'
})

// 模拟数据
const tableData = ref([
  {
    id: 1,
    name: '获取用户列表',
    path: '/api/users',
    method: 'GET',
    description: '获取系统中所有用户的列表',
    status: 1,
    createTime: '2024-01-01 10:00:00',
    requestParams: '{"page": 1, "size": 10}',
    responseExample: '{"code": 200, "data": [], "total": 0}'
  },
  {
    id: 2,
    name: '创建用户',
    path: '/api/users',
    method: 'POST',
    description: '创建新用户',
    status: 1,
    createTime: '2024-01-01 10:30:00',
    requestParams: '{"username": "test", "email": "test@example.com"}',
    responseExample: '{"code": 200, "message": "创建成功"}'
  },
  {
    id: 3,
    name: '更新用户',
    path: '/api/users/{id}',
    method: 'PUT',
    description: '更新指定用户信息',
    status: 1,
    createTime: '2024-01-01 11:00:00',
    requestParams: '{"username": "test", "email": "test@example.com"}',
    responseExample: '{"code": 200, "message": "更新成功"}'
  },
  {
    id: 4,
    name: '删除用户',
    path: '/api/users/{id}',
    method: 'DELETE',
    description: '删除指定用户',
    status: 0,
    createTime: '2024-01-01 11:30:00',
    requestParams: '{}',
    responseExample: '{"code": 200, "message": "删除成功"}'
  }
])

const apiRules = {
  name: [
    { required: true, message: '请输入接口名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入接口路径', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择请求方法', trigger: 'change' }
  ]
}

const getMethodColor = (method) => {
  const colors = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return colors[method] || 'info'
}

const handleSearch = () => {
  console.log('搜索参数:', searchForm)
  // 这里实现搜索逻辑
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    method: '',
    status: ''
  })
  handleSearch()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(apiForm, { ...row })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除API "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleTest = (row) => {
  currentApi.value = { ...row }
  testParams.value = row.requestParams || ''
  testResult.value = ''
  testDialogVisible.value = true
}

const handleStatusChange = (row) => {
  ElMessage.success(`API状态已${row.status ? '启用' : '禁用'}`)
}

const handleSubmit = async () => {
  if (!apiFormRef.value) return
  
  try {
    const valid = await apiFormRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (apiForm.id) {
      // 编辑
      const index = tableData.value.findIndex(item => item.id === apiForm.id)
      if (index > -1) {
        tableData.value[index] = { ...apiForm, createTime: tableData.value[index].createTime }
      }
      ElMessage.success('更新成功')
    } else {
      // 新增
      const newApi = {
        ...apiForm,
        id: Date.now(),
        status: 1,
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newApi)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleApiTest = async () => {
  testLoading.value = true
  
  try {
    // 模拟API测试
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟测试结果
    testResult.value = JSON.stringify({
      code: 200,
      message: '测试成功',
      data: {
        timestamp: new Date().toISOString(),
        method: currentApi.value.method,
        path: currentApi.value.path,
        params: testParams.value ? JSON.parse(testParams.value) : {}
      }
    }, null, 2)
    
    ElMessage.success('API测试完成')
  } catch (error) {
    testResult.value = JSON.stringify({
      code: 500,
      message: '测试失败',
      error: error.message
    }, null, 2)
    ElMessage.error('API测试失败')
  } finally {
    testLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(apiForm, {
    id: null,
    name: '',
    path: '',
    method: '',
    description: '',
    requestParams: '',
    responseExample: ''
  })
  if (apiFormRef.value) {
    apiFormRef.value.clearValidate()
  }
}

const handleCurrentChange = (page) => {
  pagination.page = page
  // 这里实现分页逻辑
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  // 这里实现分页逻辑
}

onMounted(() => {
  pagination.total = tableData.value.length
})
</script>

<style lang="scss" scoped>
.api-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 移动端卡片样式 */
.api-card {
  .api-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    
    .api-info {
      flex: 1;
      
      h3 {
        margin: 0 0 4px 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
      
      .api-path {
        margin: 0;
        font-size: 14px;
        color: #666;
        font-family: monospace;
        background: #f5f5f5;
        padding: 2px 6px;
        border-radius: 3px;
        display: inline-block;
      }
    }
    
    .api-status {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: flex-end;
    }
  }
  
  .api-details {
    margin-bottom: 12px;
    
    .detail-item {
      display: flex;
      margin-bottom: 6px;
      font-size: 14px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        color: #666;
        min-width: 80px;
      }
      
      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }
  
  .api-actions {
    display: flex;
    gap: 8px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
    flex-wrap: wrap;
  }
}

.api-test-container {
  .test-info {
    background: #f8f9fa;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 16px;
    
    p {
      margin: 4px 0;
      font-size: 14px;
    }
  }
  
  .test-result {
    margin-top: 16px;
    
    h4 {
      margin-bottom: 8px;
      color: #333;
    }
    
    pre {
      background: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      font-size: 12px;
      max-height: 300px;
      overflow-y: auto;
    }
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .api-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    
    .el-button {
      width: 100%;
    }
  }
}
</style>
